package com.example.demo.service;

import com.alibaba.dashscope.embeddings.TextEmbedding;
import com.alibaba.dashscope.embeddings.TextEmbeddingParam;
import com.alibaba.dashscope.embeddings.TextEmbeddingResult;
import com.example.demo.config.AliBabaEmbeddingProperties;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

@Service
public class EmbedingService {
    @Value("${embedding.model}")
    private String embedModel;

    @Autowired
    private AliBabaEmbeddingProperties aliBabaEmbeddingPropertiesConfig;

    public List<float[]> embedding(String content) throws Exception {
        TextEmbeddingParam param = TextEmbeddingParam.builder().model(TextEmbedding.Models.TEXT_EMBEDDING_V3)
                                                            .apiKey(aliBabaEmbeddingPropertiesConfig.getApiKey())
                                                            .text(content)
                                                            .build();

        TextEmbedding textEmbedding = new TextEmbedding();
        TextEmbeddingResult result = textEmbedding.call(param);
        List<Double> embeddings = result.getOutput().getEmbeddings().get(0).getEmbedding();
        List<Float> fEmbeddings = embeddings.stream().map(embed -> embed.floatValue()).toList();
        return Collections.singletonList(ArrayUtils.toPrimitive(fEmbeddings.toArray(new Float[0])));
    }
}
